package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.DEFAULT_PAGE_SIZE;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private CacheClient cacheClient;

    /**
     * 根据id查询商铺信息
     *
     * @param id
     * @return
     */
    @Override
    public Result queryById(Long id) {
        //解决缓存穿透
        //Shop shop = queryWithPassThrough(id);
        Shop shop = cacheClient.queryWithPassThrough(
                CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);

        //互斥锁解决缓存击穿
        //Shop shop = queryWithMutex(id);

        //逻辑过期解决缓存击穿
        //Shop shop = queryWithLogicalExpire(id);
        /*Shop shop = cacheClient.queryWithLogicalExpire(
                CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
*/
        if (shop == null) {
            return Result.fail("店铺不存在");
        }
        //返回结果
        return Result.ok(shop);
    }


    //预热缓存
    public void saveShop2Redis(Long id, Long expireSeconds) throws InterruptedException {
        //查询店铺数据
        Shop shop = getById(id);
        //模拟缓存重建耗时长的情况
//        Thread.sleep(20000);
        //封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        //写入redis cache
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }


    /*//逻辑过期解决缓存击穿
    private Shop queryWithLogicalExpire(Long id) {
        String key = CACHE_SHOP_KEY + id;
        //先查redis cache
        String shopJSON = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isBlank(shopJSON)) {
            //不存在，直接返回null
            return null;
        }
        //命中，存在
        //判断逻辑时间是否过期
        RedisData redisData = JSONUtil.toBean(shopJSON, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        if(redisData.getExpireTime().isAfter(LocalDateTime.now())){
            //未过期，返回商铺信息
            return shop;
        }
        //过期，需要缓存重建
        //尝试获取锁
        //判断是否获取成功
        String lockKey = LOCK_SHOP_KEY + id;
        if (tryLock(lockKey)) {
            //获取成功
            //先再次查一下cache，判断是否过期，以免自己不是第一个获取到锁的线程，也就是说其他线程这时候已经更新好了数据
            String redisDataJson = stringRedisTemplate.opsForValue().get(key);
            RedisData bean = JSONUtil.toBean(redisDataJson, RedisData.class);
            Shop reShop = JSONUtil.toBean((JSONObject) bean.getData(), Shop.class);
            if(bean.getExpireTime().isAfter(LocalDateTime.now())){
                //没过期，说明拿到的是其他线程释放的锁，缓存已经重建好了，直接返回获取到的新数据就好
                return reShop;
            }
            //如果过期，则自己是第一个，需要开启线程重建缓存，自己先返回旧数据
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    //重建缓存
                    saveShop2Redis(id,1800L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }finally {
                    //释放锁
                    unLock(lockKey);
                }
            });
        }
        //返回旧数据
        return shop;
    }

    //线程池,用于重建缓存
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    //获取锁
    public boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }


    //释放锁
    public void unLock(String key) {
        stringRedisTemplate.delete(key);
    }


    //缓存击穿
    public Shop queryWithMutex(Long id) {
        String key = CACHE_SHOP_KEY + id;
        //先查redis cache
        String shopJSON = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(shopJSON)) {
            //存在，直接返回
            Shop shop = JSONUtil.toBean(shopJSON, Shop.class);
            return shop;
        }
        //判断是否命中""空值
        if (shopJSON != null) {
            //命中""空值，直接返回
            return null;
        }
        String lockKey = null;
        Shop shop = null;
        try {
            //尝试获取锁
            lockKey = "lock:shop:" + id;
            boolean flag = tryLock(lockKey);
            //判断是否获取成功
            if (!flag) {
                //获取失败，休眠一段时间再重新查询redis（给拿到锁的那个线程一些时间去重新写入redis）
                Thread.sleep(50);
                queryWithMutex(id);
            }
            //获取成功，先查询redis cache
            String shopJSON2 = stringRedisTemplate.opsForValue().get(key);
            //存在，直接返回
            if (StrUtil.isNotBlank(shopJSON2)) {
                return JSONUtil.toBean(shopJSON2, Shop.class);
            }
            //不存在，查数据库
            shop = getById(id);
            //不存在，返回错误
            if (shop == null) {
                //不存在，写入redis cache
                stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                // TODO 这里是否需要释放锁
                //返回错误
                return null;
            }
            //存在，写入redis cache
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //释放锁
            unLock(lockKey);
        }
        //返回结果
        return shop;
    }


    //缓存穿透
    public Shop queryWithPassThrough(Long id) {
        String key = CACHE_SHOP_KEY + id;
        //先查redis cache
        String shopJSON = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(shopJSON)) {
            //存在，直接返回
            Shop shop = JSONUtil.toBean(shopJSON, Shop.class);
            return shop;
        }
        //判断是否命中""空值
        if (shopJSON != null) {
            //命中""空值，直接返回
            return null;
        }
        //不存在，查数据库
        Shop shop = getById(id);
        //不存在，返回错误
        if (shop == null) {
            //不存在，写入redis cache
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            //返回错误
            return null;
        }
        //存在，写入redis cache
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //返回结果
        return shop;
    }*/


    @Override
    @Transactional
    public Result update(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("店铺id不能为空");
        }
        //更新数据库
        updateById(shop);
        //删除redis cache
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        //判断是否需要坐标查询
        //不需要
        if (x == null || y == null) {
            // 根据类型分页查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }
        //计算分页参数
        int from = (current - 1) * DEFAULT_PAGE_SIZE;
        int end = current * DEFAULT_PAGE_SIZE;
        //根据坐标查询
        String key = SHOP_GEO_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo()
                .search(
                        key,
                        GeoReference.fromCoordinate(new Point(x, y)),
                        new Distance(5000),
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
                );
        //判断是否为空
        if (results == null) {
            return Result.ok(Collections.emptyList());
        }
        //截取from-end的部分
        List<Shop> shops = new ArrayList<>();
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if(list.size()<=from){
            //没有下一页了，结束
            return Result.ok(Collections.emptyList());
        }
        list.stream().skip(from).forEach(
                //给每一个店铺匹配相应距离
                result -> {
                    String shopIdStr = result.getContent().getName();
                    Long shopId = Long.valueOf(shopIdStr);
                    Shop shop = getById(shopId);
                    shop.setDistance(result.getDistance().getValue());
                    shops.add(shop);
                }
        );
        return Result.ok(shops);
    }
}
